package com.api.weaver.controller;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class SimpleCryptoUtil {

    private static final String ALGO = "AES";
    private static final String DEFAULT_KEY = "7fq9kb2xr8py3st6"; // 16字节固定秘钥（仅示例）
    private static final long EXPIRE_MILLIS = 5 * 60 * 1000; // 默认5分钟有效

    /**
     * 加密：明文 + 当前时间戳
     */
    public static String encryptWithTimestamp(String plainText, String key) {
        String payload = plainText + "|" + System.currentTimeMillis();
        return encrypt(payload, key);
    }

    /**
     * 解密并校验有效期
     */
    public static boolean validate(String cipherText, String expectedSecret, String key) {
        try {
            String decrypted = decrypt(cipherText, key);
            String[] parts = decrypted.split("\\|");
            if (parts.length != 2) {
                return false;
            }
            String secret = parts[0];
            long timestamp = Long.parseLong(parts[1]);

            long now = System.currentTimeMillis();
            if (!expectedSecret.equals(secret)) {
                return false; // 明文不匹配
            }
            if (now - timestamp > EXPIRE_MILLIS) {
                return false; // 超过时效
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * AES加密
     */
    public static String encrypt(String plainText, String key) {
        try {
            Cipher cipher = Cipher.getInstance(ALGO);
            SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), ALGO);
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            byte[] encrypted = cipher.doFinal(plainText.getBytes(StandardCharsets.UTF_8));
            return Base64.getEncoder().encodeToString(encrypted);
        } catch (Exception e) {
            throw new RuntimeException("加密失败", e);
        }
    }

    /**
     * AES解密
     */
    public static String decrypt(String cipherText, String key) {
        try {
            Cipher cipher = Cipher.getInstance(ALGO);
            SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), ALGO);
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            byte[] decoded = Base64.getDecoder().decode(cipherText);
            byte[] decrypted = cipher.doFinal(decoded);
            return new String(decrypted, StandardCharsets.UTF_8);
        } catch (Exception e) {
            throw new RuntimeException("解密失败", e);
        }
    }

    // 默认 key 的便捷方法
    public static String encryptWithTimestamp(String plainText) {
        return encryptWithTimestamp(plainText, DEFAULT_KEY);
    }

    public static boolean validate(String cipherText, String expectedSecret) {
        return validate(cipherText, expectedSecret, DEFAULT_KEY);
    }

    public static void main(String[] args) {
        String secret = "weaver_secret";

        // 客户端加密（带时间戳）
        String encrypted = encryptWithTimestamp(secret);
        System.out.println("加密后：" + encrypted);

        // 服务端解密 + 校验
        boolean valid = validate(encrypted, secret);
        System.out.println("校验结果：" + valid);
    }
}
